package com.xp.agent.service.mem.impl;

import java.lang.management.ManagementFactory;
import java.util.logging.Logger;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;

import com.xp.agent.service.MemService;

public class MemServiceImpl implements MemService {
	private Logger log = Logger.getLogger("MemService");
	private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
	private ObjectName tenuredMBean;

	public MemServiceImpl() {
		try {
			tenuredMBean = new ObjectName("java.lang:type=Memory");
		} catch (MalformedObjectNameException e) {
			log.info("this jvm does not support mem");
		}
	}

	@Override
	public long collect() {
		int returnCount = 0;
		try {
			CompositeData attribute = (CompositeData) mbs.getAttribute(tenuredMBean, "HeapMemoryUsage");
			return Long.parseLong(attribute.get("committed").toString());
		} catch (Throwable e) {
		}
		return returnCount;
	}

}
